<template>
  <div class="date-picker">
    <!-- 标签 -->
    <div v-if="label" class="picker-label">
      <span class="label-text">{{ label }}</span>
      <span v-if="required" class="required-mark">*</span>
      <el-tooltip v-if="tooltip" :content="tooltip" placement="top">
        <el-icon class="tooltip-icon"><QuestionFilled /></el-icon>
      </el-tooltip>
    </div>

    <!-- 日期选择器 -->
    <div class="picker-wrapper" :class="{ 'has-error': hasError }">
      <el-date-picker
        v-model="pickerValue"
        v-bind="$attrs"
        :type="type"
        :placeholder="placeholder"
        :start-placeholder="startPlaceholder"
        :end-placeholder="endPlaceholder"
        :disabled="disabled"
        :readonly="readonly"
        :clearable="clearable"
        :format="format"
        :value-format="valueFormat"
        :shortcuts="shortcuts"
        :disabled-date="disabledDate"
        :disabled-hours="disabledHours"
        :disabled-minutes="disabledMinutes"
        :disabled-seconds="disabledSeconds"
        :teleported="teleported"
        :prefix-icon="prefixIcon"
        :clear-icon="clearIcon"
        :size="size"
        @change="handleChange"
        @blur="handleBlur"
        @focus="handleFocus"
        @calendar-change="handleCalendarChange"
        @panel-change="handlePanelChange"
        @visible-change="handleVisibleChange"
      />

      <!-- 验证错误信息 -->
      <div v-if="hasError" class="error-message">
        {{ errorMessage }}
      </div>

      <!-- 帮助文本 -->
      <div v-if="helpText && !hasError" class="help-text">
        {{ helpText }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { QuestionFilled } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: [String, Number, Date, Array],
    default: "",
  },
  label: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "date",
    validator: (value) =>
      [
        "year",
        "month",
        "date",
        "dates",
        "datetime",
        "week",
        "datetimerange",
        "daterange",
        "monthrange",
      ].includes(value),
  },
  placeholder: {
    type: String,
    default: "请选择日期",
  },
  startPlaceholder: {
    type: String,
    default: "开始日期",
  },
  endPlaceholder: {
    type: String,
    default: "结束日期",
  },
  format: {
    type: String,
    default: "",
  },
  valueFormat: {
    type: String,
    default: "",
  },
  required: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: true,
  },
  shortcuts: {
    type: Array,
    default: () => [],
  },
  disabledDate: {
    type: Function,
    default: undefined,
  },
  disabledHours: {
    type: Function,
    default: undefined,
  },
  disabledMinutes: {
    type: Function,
    default: undefined,
  },
  disabledSeconds: {
    type: Function,
    default: undefined,
  },
  teleported: {
    type: Boolean,
    default: true,
  },
  prefixIcon: {
    type: [String, Object],
    default: "",
  },
  clearIcon: {
    type: [String, Object],
    default: "",
  },
  size: {
    type: String,
    default: "default",
    validator: (value) => ["large", "default", "small"].includes(value),
  },
  tooltip: {
    type: String,
    default: "",
  },
  helpText: {
    type: String,
    default: "",
  },
  rules: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits([
  "update:modelValue",
  "change",
  "blur",
  "focus",
  "calendar-change",
  "panel-change",
  "visible-change",
  "error",
  "valid",
]);

const pickerValue = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const errorMessage = ref("");
const hasError = computed(() => !!errorMessage.value);

// 验证日期值
const validate = (value) => {
  if (!props.rules.length) return true;

  for (const rule of props.rules) {
    if (rule.required) {
      const isEmpty = Array.isArray(value) ? value.some((v) => !v) : !value;
      if (isEmpty) {
        errorMessage.value = rule.message || "此项为必选项";
        return false;
      }
    }

    if (rule.validator) {
      try {
        const result = rule.validator(value);
        if (result !== true) {
          errorMessage.value = result || "验证失败";
          return false;
        }
      } catch (error) {
        errorMessage.value = error.message || "验证失败";
        return false;
      }
    }
  }

  errorMessage.value = "";
  return true;
};

// 处理日期变更
const handleChange = (value) => {
  const isValid = validate(value);
  emit("change", value);
  emit(isValid ? "valid" : "error", errorMessage.value);
};

// 处理失焦
const handleBlur = (event) => {
  emit("blur", event);
};

// 处理聚焦
const handleFocus = (event) => {
  emit("focus", event);
};

// 处理日历变更
const handleCalendarChange = (value) => {
  emit("calendar-change", value);
};

// 处理面板变更
const handlePanelChange = (date, mode) => {
  emit("panel-change", date, mode);
};

// 处理可见性变更
const handleVisibleChange = (visible) => {
  emit("visible-change", visible);
};
</script>

<style lang="scss" scoped>
.date-picker {
  @apply mb-4;

  .picker-label {
    @apply flex items-center mb-1;

    .label-text {
      @apply text-sm text-gray-700 font-medium;
    }

    .required-mark {
      @apply text-red-500 ml-1;
    }

    .tooltip-icon {
      @apply ml-1 text-gray-400 cursor-help;
    }
  }

  .picker-wrapper {
    @apply relative;

    :deep(.el-date-editor) {
      @apply w-full;
    }

    &.has-error {
      :deep(.el-input__wrapper) {
        @apply border-red-500 hover:border-red-500 focus:border-red-500;
        box-shadow: 0 0 0 1px var(--el-color-danger) inset;
      }
    }

    .error-message {
      @apply mt-1 text-sm text-red-500;
    }

    .help-text {
      @apply mt-1 text-sm text-gray-500;
    }
  }
}
</style>
